package com.apes.framework.util.monitor.druid.pool;

import com.alibaba.druid.pool.DruidDataSourceStatValue;
import com.alibaba.druid.support.monitor.MonitorClient;
import com.apes.framework.plugin.cache.Cache;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.monitor.AbstractMonitorService;
import com.apes.framework.util.monitor.Constants;
import com.apes.framework.util.monitor.MonitorUtil;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

@Service
public class DataSourceStatService extends AbstractMonitorService<DruidDataSourceStatValue> {
    private DataSourceStatValueRepository repository;
    private DataSourceStatValue statValue;

    public DataSourceStatService(DataSource dataSource, DataSourceStatValueRepository repository, Cache cache) {
        super(cache, dataSource);
        this.repository = repository;
    }

    @Override
    public void run(DruidDataSourceStatValue data) {
        if (statValue == null) {
            statValue = new DataSourceStatValue();
            statValue.setInitialSize(data.getInitialSize());
            statValue.setMinIdle(data.getMinIdle());
            statValue.setMaxActive(data.getMaxActive());
            statValue.setIp(MonitorClient.getLocalIPAddress().getHostAddress());
        }
        statValue.setActiveConnectionStackTrace(druidDataSource.getActiveConnectionStackTrace());
        //statValue.setPoolingConnectionInfo(JSONUtils.toJSONString(druidDataSource.getPoolingConnectionInfo()));
        MonitorUtil.copyAll(data, statValue, "id", "sqlList");
        statValue.setConnectionHoldTimeHistogram(data.getConnectionHoldTimeHistogram());
        statValue.setEndedOn(DateUtil.format("yyyy-MM-dd'T'HH:mm:ss.SSS") + "+0800");
        statValue = repository.save(statValue);
    }

    @Override
    protected void deleteAllData() {
        repository.deleteAll();
    }

    @Override
    public String getTopic() {
        return Constants.CONST_DRUID_SQL_ENABLE;
    }

}
